import React, { useEffect, useRef, useState, useReducer } from 'react';
import styles from './index.less';
import { Table, DatePicker, Space, message, Modal } from 'antd';
import { connect } from 'umi';
import cls from 'classnames';
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
import {
  getProjProgressBetween,
  getProjProgressBeforePlan,
  getProjProgressBeforeActual,
} from '@/services/kanbanServices';
// import { buildingUtils } from '@/utils/arcgis';
import { viewUtils } from '@/utils/arcgis';
import { buildingStatusList } from './data';
import { inExpression, likeExpression } from '@/utils/definitionExpressionHelper.js';
import Left from './left';

const { RangePicker } = DatePicker;
// import { buildingStatusTable } from './listData';

const dateFormat = 'YYYY-MM-DD';
let startTime = moment()
  .subtract(15, 'days')
  .format(dateFormat);
let endTime = moment().format(dateFormat);

const DONT_RENDER_LAYER_LIST = ['南部通道宜马三场', '宜马项目三场临建'];

const taskStatusArr = [
  '未开始',
  '未开始（延期）',
  '执行中',
  '执行中（延期）',
  '已完成',
  '已完成（提前）',
  '已完成（延期）',
].map(e => {
  return {
    text: e,
    value: e,
  };
});

const enToCn = {
  planId: '计划id',
  wbs: 'WBS编码',
  parent: '父节点',
  text: '文本描述',
  duration: '计划建设周期',
  startDate: '计划开始时间',
  endDate: '计划完成时间',
  actualDuration: '实际建设周期',
  actualStartDate: '实际开始时间',
  actualEndDate: '实际结束时间',
  finishSituation: '完成情况',
  delaySituation: '延迟情况',
  projectId: '项目id',
  taskStatus: '项目状态',
};

// 展示工程进度列表
const List = ({
  dispatch,
  // currentBimVersion,
  compareState,
  curProj,
  projProgressList,
  addedBimNameList,
  uniqValueRender,
  valueExpression,
  subLayersWithNoWbs,
  // toolbar,
  // construction,
}) => {
  // 当前数据包含可修改和不可修改
  // const [data, setData] = useState<any[]>([]);
  // const [isLoading, setIsLoading] = useState(false);
  // const [dateRange, setDateRange] = useState(['', '']);

  const dateRangeRef = useRef<string[]>([startTime, endTime]);
  const dateRef = useRef<string>(endTime);
  const [filterResultList, setFilterResultList] = useState<any[]>([]);
  const [curProgressItem, setCurProgressItem] = useState<any>(null);
  const [isShowModal, setIsShowModal] = useState(false);
  const [laterProjProgressList, setLaterProjProgressList] = useState([]); // 渲染数据的延后，渲染性能问题

  useEffect(() => {
    setTimeout(() => {
      setLaterProjProgressList(projProgressList);
    }, 800);
  }, [projProgressList]);

  useEffect(() => {
    getList();
  }, [curProj]);

  // 获取所有构件的进度
  const getList = async () => {
    // setIsLoading(true);
    // setData(fakedata);
    // setIsLoading(false);
  };

  // useEffect(() => {
  //   // 不分屏颜色渲染
  //   if (!compareState) {
  //     modelColorRender(true);
  //   } else {
  //     // 分屏清除颜色渲染
  //     modelColorRender(false);
  //   }
  // }, [compareState]);

  useEffect(() => {
    modelColorRender(true);
    // 退出全局渲染时清除value
    return () => {
      modelColorRender(false);
    };
  }, []);

  // // ! 感觉并没啥用处，默认render透明的话就已经自己隐藏
  // // 隐藏没有webs的子图层
  // useEffect(() => {
  //   console.log(subLayersWithNoWbs, '==================');
  //   subLayersWithNoWbs &&
  //     subLayersWithNoWbs.forEach(e => {
  //       e.visible = false;
  //     });
  //   return () => {
  //     subLayersWithNoWbs &&
  //       subLayersWithNoWbs.forEach(e => {
  //         e.visible = true;
  //       });
  //   };
  // }, [subLayersWithNoWbs]);

  // 获取当前加载的bim模型列表
  async function getAddedBimModelsLayers() {
    const view = await viewUtils.isViewReady();
    return addedBimNameList.reduce((r, layerName) => {
      const lyr = view.map.layers.find(l => l.title === layerName);
      if (lyr) r.push(lyr);
      return r;
    }, []);
  }

  /**
   * 模型进度颜色渲染
   * @param flag 是否渲染颜色，默认渲染
   */
  async function modelColorRender(flag = true, resetUniqValueRender = []) {
    console.time('sublayers-unique-value');
    const lyrs = await getAddedBimModelsLayers();
    lyrs.forEach(lyr => {
      // 不渲染的例外
      if (DONT_RENDER_LAYER_LIST.indexOf(lyr.title) !== -1) return;
      lyr.allSublayers.forEach(subLayer => {
        if (subLayer.type === 'building-component') {
          subLayer.renderer = {
            type: 'unique-value',
            defaultSymbol: !flag
              ? null
              : {
                  // 默认隐藏没被唯一值渲染的模型
                  // 连带作用隐藏没有wbs的子图层
                  type: 'mesh-3d',
                  symbolLayers: [
                    {
                      type: 'fill',
                      material: {
                        color: [255, 255, 255, 0.05],
                        colorMixMode: 'replace',
                      },
                    },
                  ],
                },
            valueExpression: !flag ? '' : valueExpression,
            field: 'WBS编码',
            uniqueValueInfos: !flag ? resetUniqValueRender : uniqValueRender,
          };
        }
      });
    });
    console.timeEnd('sublayers-unique-value');
  }

  // 根据时间阶段拉取建设数据
  async function _getProjProgressListBetween() {
    const [startDateTime, endDateTime] = dateRangeRef.current;
    if (!startDateTime || !endDateTime) {
      message.warn('请选择开始与结束时间');
      return;
    }
    getProjProgressBetween({
      endDateTime: endDateTime + ' 00:00:00',
      startDateTime: startDateTime + ' 00:00:00',
      projectId: curProj.projectId,
    }).then(({ data }) => {
      console.log(data);
      setTimeout(() => {
        setFilterResultList(data.data);
      }, 600);
    });
  }

  // 重置阶段选择
  function resetProjProgressList() {
    setFilterResultList([]);
  }

  // 切换分屏
  async function toggleSplitCompare() {
    function toggle() {
      dispatch({
        type: 'bimmodel/updateState',
        payload: {
          compareState: !compareState,
        },
      });
    }

    // todo
    if (!compareState) {
      // 初始化对比
      toggle();
      handleCompareDateSelected();
    } else {
      toggle();
      // 清理计划时间defineExpresstion
      renderBeforePlan(null);
      if (window.agsGlobal2.view) {
        window.agsGlobal2.view.map.removeAll();
      }
    }
  }

  // 分屏时选择时间
  function handleCompareDateSelected() {
    let dateTime = dateRef.current + ' 00:00:00';
    let projectId = curProj.projectId;
    // todo 此处是否要被注释掉？
    getProjProgressBeforePlan({ projectId, dateTime }).then(({ data }) => {
      renderBeforePlan(
        data.data.map(e => e.wbs),
        'WBS编码',
      );
    });

    getProjProgressBeforeActual({ projectId, dateTime }).then(({ data }) => {
      dispatch({
        type: 'kanban/updateState',
        payload: {
          projProgressBeforeActualList: data.data,
        },
      });
    });
  }

  async function renderBeforePlan(values = [], sqlField = '') {
    let _definitionExpression;
    if (values === null) {
      console.log('重置_definitionExpression');
      _definitionExpression = `FamilyType not in ('桥台处伸缩缝剪切','桥台处伸缩缝','桥台处伸缩缝剪切 2') `;
    } else if (!values.length) {
      _definitionExpression = `WBS编码 in ('占位占位')`;
    } else {
      _definitionExpression = likeExpression(sqlField, values);
    }
    console.log(_definitionExpression);

    const layers = await getAddedBimModelsLayers();
    layers.forEach(lyr => {
      function hideBuildingComponent(subLayer) {
        // 过滤模型
        if (subLayer.type === 'building-component') {
          subLayer.definitionExpression = _definitionExpression;
        }
      }
      lyr.allSublayers.forEach(hideBuildingComponent);
    });
  }

  function handleModalToggle(record = null) {
    if (record) {
      setCurProgressItem(record);
      setIsShowModal(true);
    } else {
      setIsShowModal(false);
    }
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      width: '60px',
      render: (text, record, index) => <span> {index + 1} </span>,
    },
    {
      title: '名称',
      dataIndex: 'text',
      align: 'left',
    },
    {
      title: '过程',
      dataIndex: 'duration',
      sorter: (a, b) => a.duration - b.duration,
      // width: '80px',
      align: 'center',
    },
    {
      title: '开始时间',
      dataIndex: 'actualStartDate',
      // sorter: (a, b) => a.actualStartDate - b.actualStartDate,
      sorter: (a, b) => {
        return (
          (new Date(a.actualStartDate).getTime() || 0) -
          (new Date(b.actualStartDate).getTime() || 0)
        );
      },
      align: 'center',
      render: actualStartDate => actualStartDate || '--',
    },
    {
      title: '结束时间',
      dataIndex: 'actualEndDate',
      // sorter: (a, b) => a.actualEndDate - b.actualEndDate,
      sorter: (a, b) => {
        return (
          (new Date(a.actualEndDate).getTime() || 0) - (new Date(b.actualEndDate).getTime() || 0)
        );
      },
      align: 'center',
      render: actualEndDate => actualEndDate || '--',
    },
    {
      title: '计划开始时间',
      dataIndex: 'startDate',
      // sorter: (a, b) =>  a.startDate > b.startDate,
      sorter: (a, b) => {
        return (new Date(a.startDate).getTime() || 0) - (new Date(b.startDate).getTime() || 0);
      },
      align: 'center',
    },
    {
      title: '计划结束时间',
      dataIndex: 'endDate',
      // sorter: (a, b) => a.endDate - b.endDate,
      sorter: (a, b) => {
        return (new Date(a.endDate).getTime() || 0) - (new Date(b.endDate).getTime() || 0);
      },
      align: 'center',
    },

    {
      title: '进度',
      dataIndex: 'taskStatus',
      align: 'center',
      filters: taskStatusArr,
      filterMultiple: false,
      onFilter: (value, record) => record.taskStatus === value,
      render: taskStatus => taskStatus || '--',
    },

    {
      title: '操作',
      align: 'center',
      render: record => {
        console.log();
        return (
          <a
            onClick={() => {
              handleModalToggle(record);
            }}
          >
            查看
          </a>
        );
      },
    },
  ];
  console.log('filterResultList',filterResultList)
  console.log('laterProjProgressList',laterProjProgressList)
  return (
    <>
      <Left />
      <div className={cls(styles.list)}>
        <div className={cls('base-panel-body')} style={{ height: 300 }}>
          <div className={cls(styles.listTitle)}>
            时间选择：
            {!compareState ? (
              <span>
                <RangePicker
                  defaultValue={[moment(startTime, dateFormat), moment(endTime, dateFormat)]}
                  format={dateFormat}
                  suffixIcon={null}
                  onChange={(_, range) => (dateRangeRef.current = range)}
                />
                <span
                  className={styles.splitBtn}
                  style={{ marginLeft: 20 }}
                  onClick={_getProjProgressListBetween}
                >
                  确定
                </span>
                <span
                  className={styles.splitBtn}
                  style={{ marginLeft: 20 }}
                  onClick={resetProjProgressList}
                >
                  重置
                </span>
              </span>
            ) : (
              <span>
                <DatePicker
                  defaultValue={moment(endTime, dateFormat)}
                  onChange={(_, dateStr) => (dateRef.current = dateStr)}
                />
                <span
                  className={styles.splitBtn}
                  style={{ marginLeft: 20 }}
                  onClick={handleCompareDateSelected}
                >
                  确定
                </span>
              </span>
            )}
            
          </div>
          <div style={{ height: '50px', lineHeight: '50px', paddingLeft: '24px' }}>
              {!compareState &&
                buildingStatusList.map(e => {
                  return (
                    <span key={e.title} className={styles.listStatus}>
                      <span
                        className={styles.listStatusColor}
                        style={{ background: e.color }}
                      ></span>
                      <span>{e.title}</span>
                    </span>
                  );
                })}
              <span onClick={toggleSplitCompare} className={styles.splitBtn}>
                分屏对比
              </span>
            </div>
          <div className={cls(styles.listContent)}>
            <Table
              rowKey="objectid"
              columns={columns}
              dataSource={filterResultList.length ? filterResultList : laterProjProgressList}
              // dataSource={filterResultList.length ? filterResultList : projProgressList}
              // dataSource={projProgressList}
              size="small"
              pagination={false}
              scroll={{ y: 210 }}
            />
          </div>

          <Modal
            title="详细信息"
            visible={isShowModal}
            onCancel={() => handleModalToggle()}
            centered
            footer={null}
            wrapClassName="progress-detail-modal"
          >
            <ul className="list">
              {!!curProgressItem &&
                Object.keys(curProgressItem).map(key => {
                  return (
                    <li className={'filed'} key={key}>
                      {enToCn[key]}: <span className="content">{curProgressItem[key]}</span>
                    </li>
                  );
                })}
            </ul>
          </Modal>
        </div>
      </div>
    </>
  );
};

export default connect(({ bimmodel, kanban, app }) => {
  return {
    currentBimVersion: bimmodel.currentBimVersion,
    compareState: bimmodel.compareState,
    addedBimNameList: bimmodel.addedBimNameList,
    // toolbar,
    // construction,
    // projProgressList: [],
    projProgressList: kanban.projProgressList,

    curProj: app.curProj,
    uniqValueRender: kanban.uniqValueRender,
    valueExpression: kanban.valueExpression,
    subLayersWithNoWbs: bimmodel.subLayersWithNoWbs,

    initUniqValueRender: kanban.initUniqValueRender,
  };
})(List);
